'use strict';

var constant = require('../../const');
var models = require('../../models');
var crypto = require('crypto');
var debug = require('debug');
var request = require('request');
var WXPay = require('weixin-pay');
var fs = require('fs');
var AV = require('leanengine')



var wxpay = WXPay({
	appid: 'wx07b56150c7843b91',
	mch_id: '1306542201',
	partner_key: 'xiaocankejiwudutuan2016zhuanqian', //微信商户平台API密钥
	pfx: fs.readFileSync(__dirname + '/apiclient_cert.p12'), //微信商户平台证书
});

function pay(req, res) {
	var ip = req.headers['x-real-ip'];
	var molianId = req.body.molianId;
	var price = req.body.price || 1;
	wxpay.createUnifiedOrder({
		body: '会员支付',
		out_trade_no: _creatTradNo(molianId),
		total_fee: 1,
		spbill_create_ip: ip,
		notify_url: 'http://wudutuantest.leanapp.cn/wxpay/notify',
		trade_type: 'NATIVE',
		product_id: '001'
	}, function(err, result) {
		res.send({
			"code_url": result.code_url
		});
	});
}

function payIndex(req, res) {
	var code_url = req.query.code_url;
	res.render('alipay/payIndex', {
		"code_url": code_url
	});
}

//{ appid: 'wx07b56150c7843b91',
// bank_type: 'CFT',
// cash_fee: '1',
// fee_type: 'CNY',
//  is_subscribe: 'Y',
//  mch_id: '1306542201',
//  nonce_str: 'emLeTWmx5ee9vBNecYktd5purBNcLHSV',
//  openid: 'oxXm8wpIq1JRJ1e4N9V8-bKEEkmI',
//  out_trade_no: '2016012078659720',
//  result_code: 'SUCCESS',
//  return_code: 'SUCCESS',
//  sign: '536BF2CDBBAAF2C83334BCA96F3E9AB7',
//  time_end: '20160120112533',
//  total_fee: '1',
//  trade_type: 'NATIVE',
//  transaction_id: '1003720667201601202797982498' }
exports.notify = wxpay.useWXCallback(function(msg, req, res, next) {
		console.log(msg);
		if (msg.result_code == "SUCCESS") {
			var sn = msg.out_trade_no;
			var price = parseInt(msg.total_fee) / 100;
			var molianId = msg.out_trade_no.substring(16);

			var query = new AV.Query(models.User);
			query.equalTo("molianId", parseInt(molianId));
			query.find({
				success: function(users) {
					if (users.length > 0) {
						var user = users[0];
						var balance = user.get('balance');
						balance += price;
						user.set('balance', balance);
						user.save(null, {
							success: function() {
								var ConsumeRecord = models.ConsumeRecord;
								var record = new ConsumeRecord();
								record.set('money', price);
								record.set('user', users[0]);
								record.set('remark', '支付' + price +"元");
								record.set('sn', sn);
								record.set('type', constant.FINANCE_TYPE_RECHARGE);
								record.save(null, {
									success: function() {
										res.success();
										//										AV.Cloud.run('sendSysMsg', {
										//											"touserId": user.id,
										//											"type": 0,
										//											"msg": "恭喜您，充值成功！充值金额若有延迟到账，退出登陆再重新登陆即可。"
										//										}, {
										//											success: function(result) {
										//												res.send({
										//													"code": 0,
										//													"msg": "发送成功"
										//												});
										//											},
										//											error: function(error) {
										//												res.send({
										//													"code": 1,
										//													"msg": "发送失败"
										//												});
										//											}
										//										});
										//										//保存记录
										//										AV.Cloud.run("incomeRecord", {
										//											"userId": user.id,
										//											"price": price,
										//											"type": constant.INCOME_TYPE_RECHARGE
										//										});
									},
									error: function(record, error) {
										console.log(error)
										res.fail()
									}
								});
							},
							error: function(user, error) {
								console.log(error);
								res.fail()
							}
						});
					}
				},
				error: function(error) {
					console.log(error);
					res.fail()
				}
			});
		}
	})

//生成订单号码
function _creatTradNo(id) {
	var time = _dataFomat(new Date());
	var num = Math.ceil(Math.random() * 99999999);
	return time + num + id;
}

function _dataFomat(date) {
	var fmt = "yyyyMMdd";
	var o = {
		"M+": date.getMonth() + 1, //月份 
		"d+": date.getDate(), //日 
		"h+": date.getHours(), //小时 
		"m+": date.getMinutes(), //分 
		"s+": date.getSeconds(), //秒 
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
		"S": date.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}



exports.pay = pay;
exports.payIndex = payIndex;